<template>
  <view class="container">
    <!-- 标题栏 -->
    <view class="header">
      <view class="header-left" @click="goBack">
        <FeatherIcon name="chevron-left" size="24" color="#333" />
      </view>
      <view class="header-title">清风明月</view>
      <view class="header-right" @click="openHelp">
        <FeatherIcon name="help-circle" size="24" color="#333" />
      </view>
    </view>

    <!-- 下拉刷新区域 -->
    <scroll-view
      scroll-y="true"
      class="breezemoon-list"
      @scrolltolower="handleLoadMore"
      refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="handleRefresh"
      @scroll="handleScroll"
    >
      <!-- 内容列表 -->
      <block v-if="breezemoons.length > 0">
        <view
          class="breezemoon-item"
          v-for="(item, index) in breezemoons"
          :key="index"
        >
          <view class="breezemoon-header">
            <image
              class="avatar"
              :src="item.breezemoonAuthorThumbnailURL48"
              mode="aspectFill"
              @click="navigateToUserProfile(item.breezemoonAuthorName)"
            ></image>
            <view class="user-info">
              <text
                class="username"
                @click="navigateToUserProfile(item.breezemoonAuthorName)"
                >{{ item.breezemoonAuthorName }}</text
              >
              <text class="time">{{
                formatTime(item.breezemoonCreated) + " " + item.breezemoonCity
              }}</text>
            </view>
          </view>
          <view class="breezemoon-content">
            <rich-text
              :nodes="formatContent(item.breezemoonContent)"
            ></rich-text>
          </view>
        </view>
      </block>

      <!-- 无内容提示 -->
      <view class="empty-tip" v-if="breezemoons.length === 0 && !loading">
        <FeatherIcon name="wind" size="60" color="#ccc" />
        <text>暂无清风明月，快来发布第一条吧</text>
      </view>

      <!-- 加载状态 -->
      <view class="loading-more" v-if="breezemoons.length > 0 || loading">
        <view class="loading-content" v-if="loading">
          <FeatherIcon
            name="loader"
            size="24"
            color="#999"
            class="loading-icon"
          />
          <text>加载中...</text>
        </view>
        <view class="loading-content" v-else-if="!hasMore">
          <text>已经到底了~</text>
        </view>
        <view class="loading-content" v-else @click="handleLoadMore">
          <text class="load-more-text">点击加载更多</text>
        </view>
      </view>
    </scroll-view>

    <!-- 右下角固定发布按钮 -->
    <view
      class="float-publish-btn"
      @click="showInputPopup"
      :class="{ hidden: isScrolling }"
    >
      <FeatherIcon name="edit-2" size="24" color="#fff" />
    </view>

    <!-- 弹出输入框 -->
    <view class="popup-mask" v-if="showPopup" @click="hideInputPopup"></view>
    <view class="popup-container" v-if="showPopup">
      <view class="popup-header">
        <text class="popup-title">发布清风明月</text>
        <view class="popup-close" @click="hideInputPopup">
          <FeatherIcon name="x" size="24" color="#666" />
        </view>
      </view>
      <view class="popup-content">
        <textarea
          class="popup-textarea"
          v-model="breezemoonContent"
          placeholder="有什么新鲜事想和大家分享？"
          maxlength="512"
          auto-focus
        ></textarea>
      </view>
      <view class="popup-footer">
        <button
          class="popup-publish-btn"
          @click="handlePublish"
          :disabled="!breezemoonContent.trim() || publishing"
        >
          <text v-if="!publishing">发布</text>
          <text v-else>发布中...</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import api from "@/api";
import { isLoggedIn } from "@/api";
import FeatherIcon from "@/components/FeatherIcon.vue";
import {
  showLoading,
  hideLoading,
  showSuccess,
  showError,
} from "@/utils/common.js";

// 发布内容
const breezemoonContent = ref("");
const publishing = ref(false);
const showPopup = ref(false);

// 清风明月列表
const breezemoons = ref([]);
const page = ref(1);
const size = ref(20);
const hasMore = ref(true);
const loading = ref(false);
const refreshing = ref(false);
const isScrolling = ref(false);
let scrollTimer = null;

// 返回上一页
const goBack = () => {
  uni.navigateBack({
    delta: 1,
  });
};

// 打开帮助页面
const openHelp = () => {
  // 跳转到解释清风明月的页面
  uni.navigateTo({
    url: `/pages/article/detail?id=1630938317106`,
  });
};

// 显示输入弹框
const showInputPopup = () => {
  if (!isLoggedIn()) {
    uni.navigateTo({
      url: "/pages/login/login",
    });
    return;
  }
  showPopup.value = true;
};

// 隐藏输入弹框
const hideInputPopup = () => {
  showPopup.value = false;
};

// 发布清风明月
const handlePublish = async () => {
  if (!breezemoonContent.value.trim() || publishing.value) return;

  try {
    publishing.value = true;
    showLoading("发布中...");

    const res = await api.breezemoons.publishBreezemoon(
      breezemoonContent.value
    );

    if (res && res.code === 0) {
      showSuccess("发布成功");
      breezemoonContent.value = "";
      hideInputPopup();
      // 重新加载数据
      page.value = 1;
      await loadBreezemoons(true);
    } else {
      showError(res?.msg || "发布失败，请稍后再试");
    }
  } catch (error) {
    console.error("发布清风明月失败", error);
    showError("发布失败，请稍后再试");
  } finally {
    publishing.value = false;
    hideLoading();
  }
};

// 加载清风明月数据
const loadBreezemoons = async (refresh = false) => {
  if (loading.value && !refresh) return;

  try {
    loading.value = true;

    if (refresh) {
      page.value = 1;
      hasMore.value = true;
    }

    const res = await api.breezemoons.getBreezemoons(page.value, size.value);

    if (res && res.code === 0) {
      const newData = res.breezemoons || [];

      if (refresh) {
        breezemoons.value = newData;
      } else {
        breezemoons.value = [...breezemoons.value, ...newData];
      }

      // 判断是否还有更多数据 - 修复：只有当返回的数据数量为0时才认为没有更多数据
      hasMore.value = newData.length > 0;

      if (hasMore.value) {
        page.value++;
      }
    } else {
      showError(res?.msg || "获取数据失败");
    }
  } catch (error) {
    console.error("加载清风明月失败", error);
  } finally {
    loading.value = false;
    if (refreshing.value) {
      refreshing.value = false;
    }
  }
};

// 加载更多
const handleLoadMore = () => {
  if (hasMore.value && !loading.value) {
    loadBreezemoons();
  }
};

// 下拉刷新
const handleRefresh = () => {
  refreshing.value = true;
  loadBreezemoons(true);
};

// 处理滚动事件
const handleScroll = () => {
  isScrolling.value = true;

  // 清除之前的定时器
  if (scrollTimer) {
    clearTimeout(scrollTimer);
  }

  // 设置新的定时器，滚动停止500ms后显示按钮
  scrollTimer = setTimeout(() => {
    isScrolling.value = false;
  }, 500);
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return "";

  const now = new Date();
  const date = new Date(timestamp);
  const diff = now - date;

  // 小于一分钟
  if (diff < 60 * 1000) {
    return "刚刚";
  }
  // 小于一小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`;
  }
  // 小于一天
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
  }
  // 小于一周
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
  }

  // 格式化年月日
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${year}-${month < 10 ? "0" + month : month}-${
    day < 10 ? "0" + day : day
  }`;
};

// 格式化内容（处理链接和图片等）
const formatContent = (content) => {
  if (!content) return "";

  try {
    // 创建一个临时的DOM元素来解析HTML
    // 注意：由于uni-app环境限制，我们使用正则表达式进行处理

    // 针对复杂的img标签问题，先尝试修复明显的错误
    let safeContent = content
      // 修复被截断的URL查询参数
      .replace(/(<img[^>]*src=["'][^"']*)(["'][^>]*>)(\?[^<]*)/g, "$1$3$2")
      // 修复常见的HTML实体
      .replace(/&lt;/g, "<")
      .replace(/&gt;/g, ">")
      .replace(/&amp;/g, "&")
      .replace(/&quot;/g, '"');

    // 简单处理：确保所有图片都有最大宽度限制
    // 匹配所有图片标签
    safeContent = safeContent.replace(/<img([^>]*)>/g, (match, attributes) => {
      // 如果已经有style属性，修改它
      if (attributes.includes("style=")) {
        return match.replace(
          /style=["']([^"']*)["']/g,
          (styleMatch, styleValue) => {
            if (!styleValue.includes("max-width")) {
              return `style="${styleValue}; max-width: 100%; border-radius: 8rpx;"`;
            }
            return styleMatch;
          }
        );
      } else {
        // 如果没有style属性，添加一个
        return `<img${attributes} style="max-width: 100%; border-radius: 8rpx;">`;
      }
    });

    // 将明显的图片URL转换为图片标签
    safeContent = safeContent.replace(
      /(?<!["'=])(https?:\/\/[^\s<]+\.(jpg|jpeg|png|gif|webp)(\?[^\s<]*)?)/gi,
      '<img src="$1" style="max-width: 100%; border-radius: 8rpx;">'
    );

    // 处理纯文本URL（排除已经处理过的图片URL）
    safeContent = safeContent.replace(
      /(?<!(href="|src="|<img[^>]*|<a[^>]*))(https?:\/\/[^\s<]+)(?!(["']|[^<]*>))/g,
      '<a href="$2" style="color: #0072ff; text-decoration: underline;">$2</a>'
    );

    return safeContent;
  } catch (error) {
    console.error("格式化内容时出错：", error);
    // 出错时返回原始内容，确保显示不会完全失败
    return content;
  }
};

// 跳转到用户主页
const navigateToUserProfile = (username) => {
  if (!username) return;

  uni.navigateTo({
    url: `/pages/user/user-profile?username=${username}`,
  });
};

// 页面加载
onMounted(() => {
  loadBreezemoons(true);
});
</script>

<style lang="scss">
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f6f7f9;
  padding-top: 180rpx; /* 为标题栏预留空间 */
}

/* 标题栏样式 */
.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 90rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20rpx;
  padding-top: 60rpx; /* 为标题栏预留空间 */
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 20;
}

.header-left,
.header-right {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

/* 清风明月列表样式 */
.breezemoon-list {
  flex: 1;
  height: 100%;
}

.breezemoon-item {
  background-color: #fff;
  margin: 0 20rpx 20rpx;
  padding: 24rpx;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .breezemoon-header {
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;

    .avatar {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      margin-right: 16rpx;
      border: 2rpx solid #f0f0f0;
    }

    .user-info {
      display: flex;
      flex-direction: column;
    }

    .username {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
    }

    .time {
      font-size: 24rpx;
      color: #999;
      margin-top: 4rpx;
    }
  }

  .breezemoon-content {
    font-size: 28rpx;
    color: #333;
    line-height: 1.6;
    word-break: break-all;
  }
}

/* 无内容提示 */
.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  color: #999;
  font-size: 28rpx;

  text {
    margin-top: 20rpx;
  }
}

/* 加载更多 */
.loading-more {
  text-align: center;
  padding: 30rpx;
  color: #999;
  font-size: 28rpx;

  .loading-content {
    display: inline-flex;
    align-items: center;
    justify-content: center;
  }

  .loading-icon {
    animation: spin 1s linear infinite;
  }

  .load-more-text {
    color: #999;
    margin-left: 8rpx;
  }

  text {
    margin-left: 8rpx;
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 右下角固定发布按钮 */
.float-publish-btn {
  position: fixed;
  right: 30rpx;
  bottom: 80rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background-color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.2);
  z-index: 10;
  transition: all 0.3s ease;

  &.hidden {
    opacity: 0;
    transform: translateX(150rpx);
    pointer-events: none;
  }
}

/* 弹出输入框样式 */
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
}

.popup-container {
  position: fixed;
  left: 30rpx;
  right: 30rpx;
  top: 25%;
  background-color: #fff;
  border-radius: 20rpx;
  z-index: 101;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.2);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  max-height: 60vh;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-close {
  padding: 10rpx;
}

.popup-content {
  padding: 30rpx;
  flex: 1;
  overflow-y: auto;
}

.popup-textarea {
  width: 100%;
  height: 240rpx;
  font-size: 28rpx;
  line-height: 1.6;
  padding: 20rpx;
  box-sizing: border-box;
  border: 1rpx solid #f0f0f0;
  border-radius: 10rpx;
  background-color: #f9f9f9;
}

.popup-footer {
  padding: 20rpx 30rpx 40rpx;
  display: flex;
  justify-content: center;
}

.popup-publish-btn {
  background-color: #ff9800;
  color: #fff;
  font-size: 28rpx;
  padding: 0;
  border-radius: 8rpx;
  border: none;
  width: 100%;
  font-weight: 400;
  text-align: center;
  height: 80rpx;
  line-height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 6rpx rgba(255, 152, 0, 0.2);

  &[disabled] {
    background-color: #e5e5e5;
    color: #999;
    box-shadow: none;
  }

  &:after {
    border: none;
  }
}
</style>
